<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Sales\Service;

use Doctrine\ORM\EntityManager;
use Sales\Entity\OrderGoodsEvaluationBase;

class OrderGoodsEvaluationBaseManager
{
    private $entityManager;

    public function __construct(
        EntityManager $entityManager
    )
    {
        $this->entityManager = $entityManager;
    }

    /**
     * 编辑修改商品评价基本表
     * @param array $data
     * @param $goodsId
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editOrderGoodsEvaluationBase(array $data, $goodsId)
    {
        $evaluationBaseInfo = $this->entityManager->getRepository(OrderGoodsEvaluationBase::class)->findOneBy(['goodsId' => $goodsId]);
        if($evaluationBaseInfo) {
            $evaluationBaseInfo->setEvaluationLastTime($data['time']);
            $evaluationBaseInfo->setEvaluationLastUser($data['userName']);
            $evaluationBaseInfo->setEvaluationCount($evaluationBaseInfo->getEvaluationCount()+1);
        } else {
            $evaluationBase = new OrderGoodsEvaluationBase();
            $evaluationBase->setGoodsId($goodsId);
            $evaluationBase->setEvaluationLastUser($data['userName']);
            $evaluationBase->setEvaluationCount(1);
            $evaluationBase->setEvaluationLastTime(time());

            $this->entityManager->persist($evaluationBase);
        }
        $this->entityManager->flush();
    }

    /**
     * 变价商品评价数量
     * @param $goodsId
     */
    public function changeOrderGoodsEvaluationBaseCount($goodsId)
    {
        $qb = $this->entityManager->createQueryBuilder();
        $qb->update(OrderGoodsEvaluationBase::class, 'b')->set('b.evaluationCount', 'b.evaluationCount-1')
            ->where('b.goodsId = :goodsId')->setParameter('goodsId', $goodsId);
        $qb->getQuery()->execute();
    }
}